<script setup>
import { Delete, Plus, Search } from '@element-plus/icons-vue'
import { ref, defineProps, watch } from 'vue'
import eventBus from '@/utils/eventBus'

const searchKey = ref('');  // 搜索依据
const searchValue = ref('');    // 搜索值

// 新增按钮点击
const addBtnClick = () => {
    eventBus.emit('addBtnClick'); // 发射事件的触发
}

const tipText = ref('请输入搜索关键字');

const props = defineProps({
    deleteMore: {
        type: Boolean,
        default: false
    },
    elOptions: {
        type: Array,
        default: () => ([])
    }
})

watch(searchKey, (newVal) => {
    const option = props.elOptions.find(item => item.value === newVal);
    tipText.value = option.text;
})

// 搜索功能
const searchBtnClick = async() => {
    eventBus.emit('searchBtnClick', {key: searchKey.value, value: searchValue.value});
}

// 监听searchValue是否还有值
watch(searchValue, (newVal) => {
    if (!newVal) {  // 如果没有值
        eventBus.emit('clearSearchBox')
    }
})
</script>

<template>
<div class="header">
    <div class="left">
        <el-button 
            type="primary" 
            plain 
            size="small"
            @click="addBtnClick"
        > 
            <el-icon><Plus /></el-icon>
            <span>新增</span>
        </el-button>
        <el-button 
            type="danger" 
            plain 
            size="small"
            v-if="deleteMore"
        >
            <el-icon><Delete /></el-icon>
            <span>批量删除</span>
        </el-button>
        <!-- 定义插槽 -->
        <slot></slot>
    </div>
    <div class="right">
        <el-select v-model="searchKey" placeholder="请选择">
            <template v-for="(item, index) of elOptions" :key="index">
                <el-option :label="item.title" :value="item.value" />
            </template>
        </el-select>
        <el-input 
            v-model="searchValue" 
            class="search_value" 
            :placeholder="tipText"
        />
        <el-button 
            type="primary" 
            @click="searchBtnClick"
            :disabled="!(searchKey&&searchValue)"
        >
            <el-icon><Search /></el-icon>
            搜素
        </el-button>
    </div>
</div>
</template>

<style scoped lang="less">
.header {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
    .right {
      .search_value {
        margin: 0 10px;
        width: 200px;
      }
    }
  }
.el-select {
  width: 120px;
}
</style>